Rail Fence Cipher
Module 01 / Lesson 07
Video Tutorial
What is a Rail Fence Cipher?
Rail Fence cipher is a simple transposition cipher that writes the message in a normal pattern on a number of "rails" (horizontal lines), then reads off each rail to create the ciphertext.
Key Components:
- Number of rails (key)
- Message text
- Normal pattern
- Reading direction
Key Rules:
- Write text down
- Write text vertical
- Read text horizontally
- Spaces are usually removed
Example with 3 Rails (Message: "CIPHERBOY")
Read text horizontally ⭢
⭣
⭣
⭣
Write message down
⭣
⭣
⭣
Write message down
C H B
I E O
P R Y
I E O
P R Y
Result: "CIPHERBOY" → "CHBIEOPRY"
Python Implementation
def rail_fence_vertical(text, rails):
text = text.replace(" ", "").upper()
# Create empty rails
fence = [[] for _ in range(rails)]
# Write the message down (vertical pattern)
for i, char in enumerate(text):
fence[i % rails].append(char)
# Read text horizontally (combine rails)
ciphertext = "".join(["".join(rail) for rail in fence])
return ciphertext
# Example
msg = "CIPHERBOY"
print(rail_fence_vertical(msg, 3)) # Output: CHBIEOPRY